package com.srmt.document.feishu.internal.writer;

import com.lark.oapi.service.docx.v1.model.Block;
import com.srmt.document.exception.DocumentOperationException;
import com.srmt.document.exception.TableException;
import com.srmt.document.feishu.internal.core.BlockContext;
import com.srmt.document.feishu.internal.table.TableOperationStrategy;
import com.srmt.document.feishu.internal.table.TableStrategyFactory;
import com.srmt.document.feishu.internal.table.model.TableContext;
import com.srmt.document.model.ColumnData;
import com.srmt.feishu.client.FeishuClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 表格列操作服务
 *
 * 负责处理表格的列级操作：添加列、追加列、删除列
 *
 * @author SRMT Development Team
 * @since 2.0.0
 */
public class TableColumnOperationService {

    private static final Logger logger = LoggerFactory.getLogger(TableColumnOperationService.class);

    private final FeishuClient client;
    private final TableStrategyFactory strategyFactory;

    /**
     * 构造函数
     *
     * @param client 飞书客户端
     */
    public TableColumnOperationService(FeishuClient client) {
        if (client == null) {
            throw new IllegalArgumentException("客户端不能为null");
        }

        this.client = client;
        this.strategyFactory = TableStrategyFactory.create(client);
    }

    /**
     * 在指定位置添加表格列
     *
     * @param docId 文档ID
     * @param anchorText 锚点文本
     * @param columns 列数据列表
     * @param startCol 起始列索引（-1表示追加到末尾）
     * @throws TableException 如果操作失败
     */
    public void addTableColumnsAfter(String docId, String anchorText, List<ColumnData> columns, int startCol)
            throws TableException {
        logger.debug("向锚点后的表格添加{}列 '{}' at column {}",
                    columns.size(), anchorText, startCol);

        try {
            // 创建上下文
            BlockContext context = new BlockContext(client, docId);

            // 查找表格
            Block tableBlock = context.findTableAfterAnchor(anchorText);
            if (tableBlock == null) {
                throw new TableException("锚点后未找到表格: " + anchorText);
            }

            // 创建表格结构获取维度信息

            // 创建表格上下文
            TableContext tableContext = new TableContext(docId, context, tableBlock);

            // 获取合适的策略
            TableOperationStrategy strategy = this.strategyFactory.getStrategy(tableBlock);

            // 调用策略方法添加列（现在接受List<ColumnData>）
            strategy.addTableColumns(tableContext, columns, startCol);

            logger.info("向表格添加了{}列", columns.size());

        } catch (DocumentOperationException e) {
            throw new TableException("添加表格列失败: " + e.getMessage());
        } catch (Exception e) {
            if (e instanceof TableException) {
                throw (TableException) e;
            }
            throw new TableException("添加表格列失败: " + e.getMessage());
        }
    }

    /**
     * 追加表格列到末尾
     *
     * @param docId 文档ID
     * @param anchorText 锚点文本
     * @param columns 列数据列表
     * @throws TableException 如果操作失败
     */
    public void appendTableColumnsAfter(String docId, String anchorText, List<ColumnData> columns)
            throws TableException {
        logger.debug("追加 {} columns to table after anchor '{}'", columns.size(), anchorText);
        addTableColumnsAfter(docId, anchorText, columns, -1);
    }

    /**
     * 删除表格列
     *
     * @param docId 文档ID
     * @param tableAnchor 表格锚点文本
     * @param startCol 起始列索引
     * @param endCol 结束列索引（包含）
     * @throws TableException 如果操作失败
     */
    public void deleteTableColumns(String docId, String tableAnchor, int startCol, int endCol)
            throws TableException {
        logger.debug("删除 columns {} to {} from table with anchor '{}'",
                    startCol, endCol, tableAnchor);

        try {
            // 创建上下文
            BlockContext context = new BlockContext(client, docId);

            // 查找表格
            Block tableBlock = context.findTableAfterAnchor(tableAnchor);
            if (tableBlock == null) {
                throw new TableException("锚点后未找到表格: " + tableAnchor);
            }

            // 创建表格上下文
            TableContext tableContext = new TableContext(docId, context, tableBlock);

            // 获取合适的策略并执行删除操作
            TableOperationStrategy strategy = this.strategyFactory.getStrategy(tableBlock);
            strategy.deleteTableColumns(tableContext, startCol, endCol);

            logger.info("删除d columns {} to {} from table", startCol, endCol);

        } catch (DocumentOperationException e) {
            throw new TableException("删除表格列失败: " + e.getMessage());
        } catch (Exception e) {
            if (e instanceof TableException) {
                throw (TableException) e;
            }
            throw new TableException("删除表格列失败: " + e.getMessage());
        }
    }
}
